package com.louis.springboot.demo.interceptor;

import com.louis.springboot.demo.utils.CusAccessObjectUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/***
 * 拦截器,单例
 */
public class BootInterceptor implements HandlerInterceptor {

    // 1
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object arg2) {
        long begin_nao_time = System.currentTimeMillis();
        String ip = CusAccessObjectUtil.getIpAddress(req);
        System.out.println(ip);
        req.setAttribute("begin_nao_time", begin_nao_time);
        req.setAttribute("p_real_ip", ip);
        return true;
    }

    /*3*/
    public void afterCompletion(HttpServletRequest req, HttpServletResponse resp, Object arg2, Exception arg3)
            throws Exception {
        long begin_nao_time = (Long) req.getAttribute("begin_nao_time");
        String real_ip = (String) req.getAttribute("p_real_ip");
        long interval = System.currentTimeMillis() - begin_nao_time;
        String uri = req.getRequestURI();
        System.out.println("------------------------");
        System.out.println("url:" + uri);
        System.out.println("IP:" + real_ip);
        System.out.println("响应时间:" + interval);
        System.out.println("------------------------");
    }

    /* 2 */
    public void postHandle(HttpServletRequest req, HttpServletResponse resp, Object arg2, ModelAndView arg3)throws Exception {}
}
